define([
    "UtilDir/util",
    "UtilDir/tool",
    "UtilDir/org/selectOrg",
    "UtilDir/searchBlock",
    "Date", "DateCN", "css!DateCss",
    "EasyUI", "EasyUI-lang"
], function (Util, Tool, SelectOrg, SearchBlock) {

    var getFxPreestimateResultController = function () {
        return getServer() + "/fx/fxPreestimateResults";
    };

    /**
     * 页面初始化
     */
    var init = function () {
        initSearchBlock();
        queryBtnBind();
        initTimeSelect();
        initMap();
    };
    var initSearchBlock = function () {
        SearchBlock.init("searchBlock");
    };
    var initTimeSelect = function () {
        $.ajax({
            url: getFxPreestimateResultController() + "/getValidDictItemsByDictCode/" + "year",
            type: "get",
            success: function (data) {
                var mySelect = document.getElementById("yearSelect");
                mySelect.add(new Option("请选择", ''), 0);
                for (var i = 0; i < data.length; i++) {
                    var name = data[i].dictItemName;
                    var code = data[i].dictItemCode;
                    mySelect.add(new Option(name, code));
                }
            }
        });
    };
    var queryBtnBind = function () {
        $("#btnSearch").click(function () {
            //createFxPreestimateDataSearchGrid();
            console.log("空间定位查询");
            var year = $("#yearSelect").val(), magnitude = $("#magnitude").val();
            //console.log("year:" + year +"-magnitude:", magnitude + "-");
            //querySpatialLocation(year, magnitude);
            $("#fx-SLQ-attributes").show();
            createSpatialLocationGrid();
        });
        $("#btnReset").click(function () {
            $("#yearSelect").val("");
            $("#magnitude").val("");
        });
        $("#fx-SLQ-Grid-Close").click(function () {
            $("#fx-SLQ-attributes").hide();
        });

        $("#fx-Area-Ssearch").click(function () {
            spatialLocationQuery();
        });
        $("#btnExport").click(function () {
            exportForm();
            //alert("导出功能暂未实现")
        });
    };
    // 导出
    var exportForm = function () {
        let year = $("#yearSelect").val();
        let magnitude = $("#magnitude").val();
        window.location.href = getFxPreestimateResultController() + "/exportSpatialLocation?year=" + year + "&magnitude="+ magnitude;
    };
    var spatialLocationQuery = function () {
        if (drawHandler) drawHandler.close();
        drawHandler = new T.PolygonTool(tdMap, drawPolygonConfig);
        drawHandler.open();
        drawHandler.addEventListener("draw", function (e) {
            var cLnglats = e.currentLnglats;
            //console.log(cLnglats);
            if (cLnglats && cLnglats.length > 2) {
                var str = "";
                for (let i = 0; i < cLnglats.length; i++) {
                    str += cLnglats[i].lng + " " + cLnglats[i].lat + ","
                }
                str += cLnglats[0].lng + " " + cLnglats[0].lat;
                console.log(str);
                $("#fx-SLQ-attributes").show();
                createSpatialLocationGrid(str);
            }
        });
    };

    var createSpatialLocationGrid = function (boundary) {
        //console.log((boundary ? ("/querySpatialLocationByBoundary?queryBoundary=" + boundary) : "/querySpatialLocation"));
        $("#fx-SLQ-Grid").datagrid({
            url: getFxPreestimateResultController() + (boundary ? ("/querySpatialLocationByBoundary?queryBoundary=" + boundary) : "/querySpatialLocation"),
            method: "GET",
            fitColumns: false,
            autoRowHeight: false,
            rownumbers: true,
            columns: [[
                {
                    field: 'workspace',
                    title: '工作区名称',
                    //width: '20%',
                    align: 'center'
                },
                {
                    field: 'year',
                    title: '年代',
                    //width: '20%',
                    align: 'center',
                },
                {
                    field: 'location',
                    title: '宏观位置',
                    //width: '20%',
                    align: 'center',
                },
                {
                    field: 'magnitude',
                    title: '震级',
                    //width: '20%',
                    align: 'center',
                },
                {
                    field: 'disasterArea',
                    title: '灾区面积<br/>(平方公里)',
                    //width: '20%',
                    align: 'center',
                },
                {
                    field: 'disasterAreaPopulation',
                    title: '灾区人口<br/>(万人)',
                    //width: '20%',
                    align: 'center',
                },
                {
                    field: 'disasterAreaGdp',
                    title: '灾区GDP<br/>(亿元)',
                    //width: '20%',
                    align: 'center',
                },
                {
                    field: 'deathNum',
                    title: '预估死亡人数<br/>（人）',
                    //width: '20%',
                    align: 'center',
                }
            ]],
            queryParams: {
                year: $("#yearSelect").val(),
                magnitude: $("#magnitude").val()
            },
            pagination: true,
            pageSize: 10,
            onLoadSuccess: function (result) {
                console.log("datagrid: ", result);
                tdMap.clearOverLays();
                global_markers = [];
                var data = result.rows;
                if (data && data.length) {
                    var points = [];
                    for (let i = 0; i < data.length; i++) {
                        icon = new T.Icon({iconUrl: "/fxpg/static/app/fxpg/fx_plugins/images/marker-red.png", iconSize: new T.Point(20, 20), iconAnchor: new T.Point(-10, -10)})
                        var point = new T.LngLat(data[i].longitude, data[i].latitude);
                        var marker = new T.Marker(point, {icon: icon, _data: data[i], _rowIndex: i});
                        marker.addEventListener("click", spatialLocationMarkerClick);
                        tdMap.addOverLay(marker);
                        points.push(point);
                        global_markers.push(marker);
                    }
                    tdMap.setViewport(points);
                }
            },
            onClickRow: function (index, rowData) {
                console.log(index, rowData);
                //tdMap.panTo(new T.LngLat(rowData.longitude, rowData.latitude));
                hilighRowAndMarker($(this), index);
            }
        });
    };
    var spatialLocationMarkerClick = function () {
        var _data = this.options._data, _rowIndex = this.options._rowIndex, fxSLQGrid = $('#fx-SLQ-Grid');
        //console.log(_rowIndex);
        var row = fxSLQGrid.datagrid('getRows')[_rowIndex];
        console.log(_data);
        //tdMap.panTo(new T.LngLat(row.longitude, row.latitude));
        hilighRowAndMarker(fxSLQGrid, _rowIndex);

        $('.datagrid-view2 .datagrid-body .datagrid-row').eq(_rowIndex)[0].scrollIntoView(true);
    };
    var hilighRowAndMarker = function (grid, index) {
        var opt = grid.datagrid("options");
        //var rows1 = opt.finder.getTr(this,"","allbody",1);
        var rows2 = opt.finder.getTr(grid.get(0),"","allbody",2);
        //$(rows1).eq(index).addClass('datagrid-row-click').siblings().removeClass('datagrid-row-click');
        $(rows2).eq(index).addClass('datagrid-row-click').siblings().removeClass('datagrid-row-click');

        icon = new T.Icon({iconUrl: "/fxpg/static/app/fxpg/fx_plugins/images/marker-blue.png", iconSize: new T.Point(20, 20), iconAnchor: new T.Point(-10, -10)});
        var cMarker = global_markers[index];
        cMarker.setIcon(icon);
        //console.log("global_pre_marker: ", global_pre_marker);
        if (global_pre_marker && (cMarker.options._rowIndex != global_pre_marker.options._rowIndex)) {
            icon = new T.Icon({iconUrl: "/fxpg/static/app/fxpg/fx_plugins/images/marker-red.png", iconSize: new T.Point(20, 20), iconAnchor: new T.Point(-10, -10)})
            global_pre_marker.setIcon(icon);
        }
        global_pre_marker = global_markers[index];
    };

    var tdMap, icon;
    var global_pre_marker, global_markers = [];
    var drawHandler, drawPolygonConfig = {showLabel: false, color: "blue", weight: 3, opacity: 0.5, fillColor: "#FFFFFF", fillOpacity: 0.5};
    var initMap = function () {
        var mapH = document.body.clientHeight - $(".pd-search-container").height() - 20;
        $("#fx-SLQ-mapDiv").height(mapH);

        var vec_layer = new T.TileLayer("https://fxpc.mem.gov.cn/data_preparation/171dd1d5-bbb3-483a-a7f6-50d6d98cee1f/d9ffc071-50dd-4780-a617-673d17921e22/wmts?service=wmts&request=gettile&version=1.0.0&layer=vec&style=default&tilematrixset=c&format=tiles&tilematrix={z}&tilerow={y}&tilecol={x}&geokey=94E99EB4FEB9B48CD5348F7BCF5BB620");
        var cva_layer = new T.TileLayer("https://fxpc.mem.gov.cn/data_preparation/171dd1d5-bbb3-483a-a7f6-50d6d98cee1f/13f8b69d-98dc-4276-bbf0-9c4c372acabc/wmts?service=wmts&request=gettile&version=1.0.0&layer=cva&style=default&tilematrixset=c&format=tiles&tilematrix={z}&tilerow={y}&tilecol={x}&geokey=94E99EB4FEB9B48CD5348F7BCF5BB620");
        var config = {
            projection: 'EPSG:4326',
            minZoom: 4,
            layers: [vec_layer, cva_layer]
        };
        tdMap = new T.Map('fx-SLQ-mapDiv', config), zoom = 4;
        tdMap.centerAndZoom(new T.LngLat(106.34766, 34.37971), zoom);

    };








    return {
        init: init
    };
});
